<template>
  <div ref="wrapRef" class="ellipsis-text">
    <Tooltip v-if="isEllipsis" placement="topLeft" :title="text">
      <div class="ellipsis-text-true">{{ text }}</div>
    </Tooltip>
    <div v-else class="ellipsis-text-true" :class="{ 'is-ellipsis': isEllipsis }">{{ text }}</div>
    <div ref="falseRef" class="ellipsis-text-false">{{ text }}</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Tooltip } from 'ant-design-vue'

defineProps<{
  text: string
}>()

const wrapRef = ref<HTMLElement | null>(null)
const falseRef = ref<HTMLElement | null>(null)
const isEllipsis = ref(false)

onMounted(() => {
  if (wrapRef.value && falseRef.value) {
    const wrapWidth = wrapRef.value.clientWidth
    const textWidth = falseRef.value.clientWidth
    isEllipsis.value = textWidth > wrapWidth
  }
})
</script>

<style scoped lang="less">
.ellipsis-text {
  width: 100%;
  position: relative;
  &-true:not(.is-ellipsis) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  &-false {
    opacity: 0;
    position: absolute;
    top: 0;
    left: 0;
    white-space: nowrap;
    z-index: -1;
  }
}
</style>
